package com.boomsecret.classloader.encode;

import com.boomsecret.utils.DesUtils;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Objects;

/**
 * Created by wangjinliang on 2018/1/31.
 */
public class ClassFileEncodeDemo {
    @Test
    public void loadEncodeFile() {
        EncodeClassLoader classLoader = new EncodeClassLoader();
        String filePath = "C:\\MineProjects\\JavaDemo\\";
        String name = "com.boomsecret.classloader.encode.UserDao";
        try {
            Class<IUserDao> userDaoClass = (Class<IUserDao>) classLoader.findClassByFilePathAndName(filePath, name);
            IUserDao userDao = userDaoClass.newInstance();
            userDao.save(new User());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void createEncodeFile() {
        String targetFilePath = "C:\\MineProjects\\JavaDemo\\target\\classes\\com\\boomsecret\\classloader\\encode\\UserDao.class";
        String encodedFilePath = "C:\\MineProjects\\JavaDemo\\UserDao.class";
        FileInputStream fis = null;
        FileOutputStream fos = null;
        ByteArrayOutputStream baos = null;
        try {
            fis = new FileInputStream(new File(targetFilePath));
            fos = new FileOutputStream(new File(encodedFilePath));
            baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = fis.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            byte[] encode = DesUtils.encode(baos.toByteArray());
            fos.write(encode);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(fis)) {
                try {
                    fis.close();
                } catch (Exception e) {}
            }
            if (Objects.nonNull(fos)) {
                try {
                    fos.close();
                } catch (Exception e) {}
            }
            if (Objects.nonNull(baos)) {
                try {
                    baos.close();
                } catch (Exception e) {}
            }
        }
    }
}
